package org.cms.cmsweb.captcha;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
 
public class CaptchaFormAuthenticationFilter extends FormAuthenticationFilter{
      public static final String DEFAULT_CAPTCHA_PARAM = "captcha";
      public static final String DEFAULT_IP_PARAM="ip";
      private String captchaParam =DEFAULT_CAPTCHA_PARAM;
      private String ipParam =DEFAULT_IP_PARAM;
      public String getCaptchaParam() {
        return captchaParam;
    }
      
      public String getIpParam() {
          return ipParam;
      }
      protected String getCaptcha(ServletRequest request) {
        return WebUtils.getCleanParam(request, getCaptchaParam());
    }
      
   
  protected AuthenticationToken createToken(
       ServletRequest request, ServletResponse response) {
        String username = getUsername(request);
        String password = getPassword(request);
        String captcha = getCaptcha(request);

        boolean rememberMe = isRememberMe(request);
        String host = getHost(request);
               
        return new CaptchaUsernamePasswordToken(username, password, rememberMe, host,captcha);
    }
  
  public String getIpAddrByRequest(HttpServletRequest request) {  

	         String ip = request.getHeader("x-forwarded-for");  

	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  

	           ip = request.getHeader("Proxy-Client-IP");  

	         }  

	         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  

	            ip = request.getHeader("WL-Proxy-Client-IP");  

	          }  

	           if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  

	              ip = request.getRemoteAddr();  

	          }  

	         return ip;  

	    } 

 
}